Cayetano Romero Monteagudo (caromon3@alumni.uv.es)
Alejandro García Segarra (agarse4@alumni.uv.es)
Carlos García Castilla (garcas8@alumni.uv.es).
Universitat de ValènciaTrabajo elaborado para la asignatura “Programación y manejo de datos en la era del Big Data” de la Universitat de València durante el curso 2021-2022. El repo del trabajo está aquí.
La página web de la asignatura y los trabajos de mis compañeros pueden verse aquí.
#---PREPARACION DE LOS DATOS
pilotos <- rio::import(file = "./datos/drivers.csv")
resultados <- rio::import(file = "./datos/results.csv")
#str(resultados)
#str(pilotos)
#pilotos[, c(1)] <- sapply(pilotos[, c(1)], as.numeric)
#resultados[, c(3,6,9)] <- sapply(resultados[, c(3,6,9)], as.numeric)
#----------------------------------------------------------------------------------
#numero de carreras que ha corrido cada piloto
#explicacion de lo que hago, no se porque la variable sumatorio no la detecta como numerica aunque la pase a numerica, por tanto al ordenar con slice max no funciona, lo que he hecho es usar la funcion arrange, que ordena de menor a mayor, pero como queremos los que mas carreras han corrido, no me sirve de menor a mayor, por tanto he multiplicado la variable del sumatorio por -1, he usado arrange para que los que más carreras tienen salgan primero, y luego he vuelto a multiplicar por -1. luego he cogido mayores de 202 carreras, que son los 20 que más tienen, porque si hago slice se descuadra y te devuelve el df del principio
n_carreras <- resultados %>% group_by(driverId) %>% mutate(numero_carreras = sum(n())) %>% distinct(numero_carreras) %>% arrange(desc(numero_carreras)) #mutate(numero_carreras_final = numero_carreras*-1)
n_carreras_nom <- full_join(n_carreras, pilotos, c ("driverId" = "driverId")) %>% select(driverId, driverRef, numero_carreras) %>% filter(numero_carreras >= 202 ) #los 20 qque mas carreras tienen (no funciona usar slice_max)
#--------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# numero de victorias por piloto
victorias <- resultados %>% filter(position == "1") %>% group_by(driverId) %>% mutate(n_victorias = sum(n())) %>% distinct(n_victorias) %>% arrange(desc(n_victorias))#mutate(n_victorias_final = n_victorias*-1)
#aqui fusiono con el df de pilotos para que aparezca el nombre y no sólo el ID del piloto en cuestion, y hago lo mismo que en el apartado de arriba para ordenar
victorias_con_nombre <- full_join(victorias, pilotos, c ("driverId" = "driverId")) %>% select(driverId, nationality, driverRef, n_victorias) #los 10 con mas victorias, tmp funciona slice_max
mas_victorias <- victorias_con_nombre %>% filter(n_victorias >= 25 )
#-------------------------------------------------
#resultado medio
str(resultados)
#> 'data.frame': 25140 obs. of 18 variables:
#> $ resultId : int 1 2 3 4 5 6 7 8 9 10 ...
#> $ raceId : int 18 18 18 18 18 18 18 18 18 18 ...
#> $ driverId : int 1 2 3 4 5 6 7 8 9 10 ...
#> $ constructorId : int 1 2 3 4 1 3 5 6 2 7 ...
#> $ number : chr "22" "3" "7" "5" ...
#> $ grid : int 1 5 7 11 3 13 17 15 2 18 ...
#> $ position : chr "1" "2" "3" "4" ...
#> $ positionText : chr "1" "2" "3" "4" ...
#> $ positionOrder : int 1 2 3 4 5 6 7 8 9 10 ...
#> $ points : num 10 8 6 5 4 3 2 1 0 0 ...
#> $ laps : int 58 58 58 58 58 57 55 53 47 43 ...
#> $ time : chr "1:34:50.616" "+5.478" "+8.163" "+17.181" ...
#> $ milliseconds : chr "5690616" "5696094" "5698779" "5707797" ...
#> $ fastestLap : chr "39" "41" "41" "58" ...
#> $ rank : chr "2" "3" "5" "7" ...
#> $ fastestLapTime : chr "1:27.452" "1:27.739" "1:28.090" "1:28.603" ...
#> $ fastestLapSpeed: chr "218.300" "217.586" "216.719" "215.464" ...
#> $ statusId : int 1 1 1 1 1 11 5 5 4 3 ...
resultados[, c(7)] <- sapply(resultados[, c(7)], as.numeric)
resultados[is.na(resultados)] <- 25
resultado_medio <- full_join(pilotos, resultados, c ("driverId" = "driverId")) %>% select(driverId, driverRef, position) %>% group_by(driverId) %>% mutate(result_medio = mean(position)) %>% distinct (driverId, driverRef, result_medio) %>% arrange(result_medio)
#resultado medio en clasificacion
resultado_medio_clas <- full_join(pilotos, resultados, c ("driverId" = "driverId")) %>% select(driverId, driverRef, grid) %>% group_by(driverId) %>% mutate(result_medio_clas = mean(grid)) %>% distinct (driverId, driverRef, result_medio_clas) %>% filter(result_medio_clas > 0) %>% arrange(result_medio_clas)
#numero de vueltas liderando
#puntos por carrera (puntos/carrera)
puntos_x_carrera <- full_join(pilotos, resultados, c ("driverId" = "driverId")) %>% select(driverId, driverRef, points) %>% full_join(., n_carreras, c ("driverId" = "driverId")) %>% group_by(driverId) %>% mutate(total_puntos = sum(points)) %>% distinct(driverId, driverRef, numero_carreras, total_puntos) %>% mutate(media_puntos = total_puntos/numero_carreras) %>% arrange(desc(media_puntos))
objetos_no_borrar <- c("victorias_con_nombre", "n_carreras_nom", "mas_victorias")
rm(list = ls()[!ls() %in% objetos_no_borrar])#se necesita "mas_victorias"
gg_mas_victorias <- ggplot(mas_victorias, aes(x = reorder(driverRef, n_victorias), y = n_victorias )) + geom_bar(stat = "identity") + labs(x = "Piloto" , y = "Número de victorias")
gg_mas_victorias
#trabajo --> darle formato chulo, ya veremos este puente si le podemos meter dinámico o que
objetos_no_borrar <- c("victorias_con_nombre", "n_carreras_nom")
rm(list = ls()[!ls() %in% objetos_no_borrar]) #--------------------------------------------------------------------------------------
#pilotos españoles
pilotos <- rio::import(file = "./datos/drivers.csv")
pilotos_esp <- pilotos %>% filter(nationality == "Spanish") %>% select(driverId, driverRef, nationality)
#mas victorias de pilotos españoles
mas_victorias_esp <- full_join(victorias_con_nombre, pilotos, c ("driverId" = "driverId")) %>% filter(nationality.x == "Spanish") %>% select(driverId, driverRef.x, n_victorias, nationality.x)
objetos_no_borrar <- c("victorias_con_nombre", "n_carreras_nom", "mas_victorias")
rm(list = ls()[!ls() %in% objetos_no_borrar])
#-------------------------------------------------------------------------------------------#datos de escuderias pa quien quiera hacer algo
#escuderias <- rio::import(file = "./datos/constructors.csv")
#escuderias2 <- rio::import(file = "./datos/constructor_standings.csv")
#result_escuderias <- rio::import(file = "./datos/constructor_results.csv")
#pilotos <- rio::import(file = "./datos/drivers.csv")
#resultados <- rio::import(file = "./datos/results.csv")
#carreras <- rio::import(file = "./datos/races.csv")
#escuderiasesp <- escuderias %>% filter(nationality == "Spanish") #escuderias españolas
#campeones_esc <- full_join(pilotos, resultados, c("driverId" = "driverId")) %>% full_join(., carreras, c("raceId" = "raceId")) %>% select(driverId, driverRef, nationality, constructorId, points, year, round) %>% full_join(., escuderias, c("constructorId" = "constructorId")) %>% select(driverId, driverRef, nationality.x, constructorId, points, year, name, round) %>% group_by(year, driverRef) %>% mutate(puntos_totales = cumsum(points)) %>% ungroup() %>% group_by(year) %>% slice_max(puntos_totales, n=1) %>% select(name, driverRef) %>% group_by(name, driverRef) %>% mutate(total_camp = sum( NN = n())) %>% arrange(name)
#campeones_esc <- campeones_esc[!(campeones_esc$driverRef == 'max_verstappen'),]
#library(treemap)
#library(d3treeR)
# basic treemap
#gg_esc_campeones <- treemap(campeones_esc,
#index=c("name","driverRef"),
#vSize="total_camp",
#type="index",
#vColor = "name",
#palette = "Set2",
#align.labels=list(
#c("center", "center"),
#c("center", "bottom")),
#title = "Escuderías con más campeones",
#title.legend = "Escuderías") inter_camp <- d3tree2(gg_esc_campeones , rootname = "Escuderías y Campeones" )
inter_camp#alonso vs compañeros de equipo
pilotos <- rio::import(file = "./datos/drivers.csv")
resultados <- rio::import(file = "./datos/results.csv")
escuderias <- rio::import(file = "./datos/constructors.csv")
carreras <- rio::import(file = "./datos/races.csv")
alovsall <- full_join(pilotos, resultados, c ("driverId" = "driverId")) %>% select(driverRef, resultId, raceId, constructorId, position, points) %>% full_join(., escuderias, c ("constructorId" = "constructorId")) %>% select(driverRef, resultId, raceId, constructorId, position, position, points, name) %>% full_join(., carreras, c ("raceId" = "raceId")) %>% select(driverRef, resultId, raceId, constructorId, position, position, points, name.x, year, round)
#alo_vs_marques <- alovsall %>% filter(year == 2001, driverRef %in% c("alonso", "marques"), round <= 14)
alo_vs_trulli <- alovsall %>% filter(year %in% c(2003, 2004), driverRef %in% c("alonso", "trulli")) %>% slice(1:15, 17:67) %>% group_by(driverRef, year) %>% mutate(puntos_acumulados = cumsum(points)) %>% ungroup()
alo_vs_fisichella <- alovsall %>% filter(year %in% c(2005, 2006), driverRef %in% c("alonso", "fisichella")) %>% group_by(driverRef, year) %>% mutate(puntos_acumulados = cumsum(points)) %>% ungroup()
alo_vs_hamilton <- alovsall %>% filter(year %in% c(2007) ,driverRef %in% c("alonso", "hamilton")) %>% group_by(driverRef, year) %>% mutate(puntos_acumulados = cumsum(points)) %>% ungroup()
alo_vs_piquet <- alovsall %>% filter(year %in% c(2008, 2009), driverRef %in% c("alonso", "piquet_jr")) %>% slice(1:28, 36:63) %>% group_by(driverRef, year) %>% mutate(puntos_acumulados = cumsum(points)) %>% ungroup()
#alo_vs_grosjean <- alovsall %>% filter(year == 2009, driverRef %in% c("alonso", "grosjean"), round >= 11)
alo_vs_massa <- alovsall %>% filter(year %in% c(2010, 2011, 2013), driverRef %in% c("alonso", "massa")) %>% group_by(driverRef, year) %>% mutate(puntos_acumulados = cumsum(points)) %>% ungroup()
alo_vs_raikkonen <- alovsall %>% filter(year == 2014, driverRef %in% c("alonso", "raikkonen")) %>% group_by(driverRef, year) %>% mutate(puntos_acumulados = cumsum(points)) %>% ungroup()
alo_vs_button <- alovsall %>% filter(year %in% c(2015, 2016), driverRef %in% c("alonso", "button")) %>% group_by(driverRef, year) %>% mutate(puntos_acumulados = cumsum(points)) %>% ungroup()
alo_vs_vandoorne <- alovsall %>% filter(year %in% c(2017, 2018), driverRef %in% c("alonso", "vandoorne")) %>% slice(1:45, 47:81) %>% group_by(driverRef, year) %>% mutate(puntos_acumulados = cumsum(points))%>% ungroup()
alo_vs_ocon <- alovsall %>% filter(year == 2021, driverRef %in% c("alonso", "ocon")) %>% group_by(driverRef, year) %>% mutate(puntos_acumulados = cumsum(points)) %>% ungroup()
ALO_VS_ALL <- full_join(alo_vs_trulli, alo_vs_fisichella, c("driverRef"= "driverRef", "resultId" = "resultId", "raceId" = "raceId", "constructorId" = "constructorId", "position" = "position", "points" = "points", "name.x" = "name.x", "year" = "year", "round" = "round" , "puntos_acumulados" = "puntos_acumulados")) %>%
full_join(., alo_vs_hamilton, c("driverRef"= "driverRef", "resultId" = "resultId", "raceId" = "raceId", "constructorId" = "constructorId", "position" = "position", "points" = "points", "name.x" = "name.x", "year" = "year", "round" = "round", "puntos_acumulados" = "puntos_acumulados")) %>%
full_join(., alo_vs_piquet, c("driverRef"= "driverRef", "resultId" = "resultId", "raceId" = "raceId", "constructorId" = "constructorId", "position" = "position", "points" = "points", "name.x" = "name.x", "year" = "year", "round" = "round", "puntos_acumulados" = "puntos_acumulados")) %>%
full_join(., alo_vs_massa, c("driverRef"= "driverRef", "resultId" = "resultId", "raceId" = "raceId", "constructorId" = "constructorId", "position" = "position", "points" = "points", "name.x" = "name.x", "year" = "year", "round" = "round", "puntos_acumulados" = "puntos_acumulados")) %>%
full_join(., alo_vs_raikkonen, c("driverRef"= "driverRef", "resultId" = "resultId", "raceId" = "raceId", "constructorId" = "constructorId", "position" = "position", "points" = "points", "name.x" = "name.x", "year" = "year", "round" = "round", "puntos_acumulados" = "puntos_acumulados")) %>%
full_join(., alo_vs_button, c("driverRef"= "driverRef", "resultId" = "resultId", "raceId" = "raceId", "constructorId" = "constructorId", "position" = "position", "points" = "points", "name.x" = "name.x", "year" = "year", "round" = "round", "puntos_acumulados" = "puntos_acumulados")) %>%
full_join(., alo_vs_vandoorne, c("driverRef"= "driverRef", "resultId" = "resultId", "raceId" = "raceId", "constructorId" = "constructorId", "position" = "position", "points" = "points", "name.x" = "name.x", "year" = "year", "round" = "round", "puntos_acumulados" = "puntos_acumulados")) %>%
full_join(., alo_vs_ocon, c("driverRef"= "driverRef", "resultId" = "resultId", "raceId" = "raceId", "constructorId" = "constructorId", "position" = "position", "points" = "points", "name.x" = "name.x", "year" = "year", "round" = "round", "puntos_acumulados" = "puntos_acumulados"))
objetos_no_borrar <- c("ALO_VS_ALL", "n_carreras_nom", "victorias_con_nombre")
rm(list = ls()[!ls() %in% objetos_no_borrar])
gc() #instruccion para que cargue el grafico, al ser tan complejo da error de no sé qué pero con esto funciona
#> used (Mb) gc trigger (Mb) max used (Mb)
#> Ncells 1685519 90.1 3413672 182.4 3413672 182.4
#> Vcells 2969289 22.7 8388608 64.0 7648330 58.4
ggalo_vs_all <- ggplot(data = ALO_VS_ALL, aes(round, puntos_acumulados, color = driverRef)) +
geom_line() +
geom_point() +
labs(title = "Alonso contra el mundo",
subtitle = "le das un carton con ruedas y aún te saca puntos",
y = "Puntos", x = "") + facet_wrap( ~ year) + transition_reveal(round)
#ggalo_vs_all
objetos_no_borrar <- c("victorias_con_nombre", "n_carreras_nom", "mas_victorias")
rm(list = ls()[!ls() %in% objetos_no_borrar])pilotos <- rio::import(file = "./datos/drivers.csv")
resultados <- rio::import(file = "./datos/results.csv")
escuderias <- rio::import(file = "./datos/constructors.csv")
carreras <- rio::import(file = "./datos/races.csv")
campeones <- full_join(pilotos, resultados, c("driverId" = "driverId")) %>% full_join(., carreras, c("raceId" = "raceId")) %>% select(driverId, driverRef, nationality, constructorId, points, year, round) %>% full_join(., escuderias, c("constructorId" = "constructorId")) %>% select(driverId, driverRef, nationality.x, constructorId, points, year, name, round) %>% group_by(year, driverRef) %>% mutate(puntos_totales = cumsum(points)) %>% ungroup() %>% group_by(year) %>% slice_max(puntos_totales, n=1) %>% ungroup() %>% group_by(driverRef)%>% mutate(total_campeonatos = sum(NN = n())) %>% distinct(driverRef, nationality.x, total_campeonatos) %>% arrange(nationality.x, total_campeonatos) #me quedo por aqui
campeones <- campeones[!(campeones$driverRef == 'max_verstappen'),]
id <- rownames(campeones)
campeones <- cbind(id=id, campeones)
campeones[, c(1)] <- sapply(campeones[, c(1)], as.numeric)
label_campeones <- campeones
number_of_bar <- nrow(label_campeones)
angle <- 90 - 360 * (label_campeones$id-0.5) /number_of_bar # I substract 0.5 because the letter must have the angle of the center of the bars. Not extreme right(1) or extreme left (0)
label_campeones$hjust <- ifelse( angle < -90, 1, 0)
label_campeones$angle <- ifelse(angle < -90, angle+180, angle)
base_campeones <- campeones %>%
group_by(nationality.x) %>%
summarise(start=min(id), end=max(id)) %>%
rowwise() %>%
mutate(title=mean(c(start, end)))
grid_campeones <- base_campeones
grid_campeones$end <- grid_campeones$end[ c( nrow(grid_campeones), 1:nrow(grid_campeones)-1)] + 1
grid_campeones$start <- grid_campeones$start - 1
grid_campeones <- grid_campeones[-1,]
p <- ggplot(campeones, aes(x=as.factor(year), y=total_campeonatos, fill=nationality.x, color = nationality.x)) + geom_bar(aes(x=as.factor(id), y=total_campeonatos, fill=nationality.x), stat="identity", alpha=0.5) +# Add a val=100/75/50/25 lines. I do it at the beginning to make sur barplots are OVER it.
geom_segment(data=grid_campeones, aes(x = 0, y = 8, xend = 31, yend = 8), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 0, y = 6, xend = 31, yend = 6), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 0, y = 4, xend = 31, yend = 4), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 0, y = 2, xend = 31, yend = 2), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
# Add text showing the value of each 100/75/50/25 lines
annotate("text", x = rep(max(campeones$id),4), y = c(2, 4, 6, 8), label = c("2", "4", "6", "8") , color="grey", size=3 , angle=0, fontface="bold", hjust=1) +
geom_bar(aes(x=as.factor(id), y=total_campeonatos, fill=nationality.x), stat="identity", alpha=0.5) +
ylim(-10,21) +
theme_minimal() +
theme(
legend.position = "none",
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
plot.margin = unit(rep(-1,4), "cm") ) +
coord_polar() +
geom_text(data=label_campeones, aes(x=id, y=10, label=driverRef, hjust=hjust), color="black", fontface="bold",alpha=0.6, size=2.5, angle= label_campeones$angle, inherit.aes = FALSE ) +
# Add base line information
geom_segment(data=grid_campeones, aes(x = 0.70, y = -1, xend = 2.45, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 2.6, y = -1, xend = 3.55, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 3.65, y = -1, xend = 5.45, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 5.55, y = -1, xend = 7.35, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 7.5, y = -1, xend = 10.50, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 10.7, y = -1, xend = 19.20, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 19.4, y = -1, xend = 20.3, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 20.45, y = -1, xend = 23.4, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 23.65, y = -1, xend = 24.35, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 24.60, y = -1, xend = 27, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 27.2, y = -1, xend = 29.5, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 29.7, y = -1, xend = 30.5, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 30.7, y = -1, xend = 31.5, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_campeones, aes(x = 31.7, y = -1, xend = 32.5, yend = -1), colour = "black", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_text(data=base_campeones, aes(x = title, y = -18, label=nationality.x), hjust=c(1,1,0,0), colour = "black", alpha=0.8, size=4, fontface="bold", inherit.aes = FALSE)
#p carreras <- rio::import(file = "./datos/races.csv")
circuitos <- rio::import(file = "./datos/circuits.csv")
carreras_21 <- full_join(carreras,circuitos, c("circuitId" = "circuitId")) %>%
filter(year=="2020") %>%
select(round, name.x, name.y, date, location,country, lat, lng, alt) %>%
arrange(round) %>%
mutate(round2 = round)
carreras_21_v2 <- carreras_21[, c(1, 4, 10, 2, 3, 5, 6, 7, 8, 9)]
carreras_21_v2 <- carreras_21_v2%>% unite(. ,variables, c(1, 5, 7), sep = "; ")
#pruebas para mapas, no ejecutar de momento
#library(widgetframe)
#library(leaflet)
#l <- leaflet() %>% setView(lat = 45.61560, lng = 9.281110, zoom=1)
#frameWidget(l)
#mapaCiudadyPueblomayorinciAcu <- leaflet() %>%
# setView(lng = -0.243591, lat = 38.821, zoom = 7) %>%
#addMarkers(lng = -0.243591, lat = 38.821 , popup = "Vall de Gallinera")%>%
#setView(lng = -0.418598, lat = 40.2011, zoom = 7) %>%
#addMarkers(lng = -0.418598, lat = 40.2011 , popup = "Villahermosa del rio") %>% addTiles()
#mapaCiudadyPueblomayorinciAcu
#MAPA DEL MUNDO DE LA OSTIA NO TOCAR, pongo como comentario para que no tarde tanto al knitear
globo_circ <-create_globe() %>% globe_pov(45.61560, 9.281110) %>% globe_bars(coords(lat, lng, label = variables, color = round2), data = carreras_21_v2) %>% scale_bars_color()
#globo_circ
objetos_no_borrar <- c("victorias_con_nombre", "n_carreras_nom", "mas_victorias")
rm(list = ls()[!ls() %in% objetos_no_borrar])circuitos <- rio::import(file = "./datos/circuits.csv")
tiempos <- rio::import(file = "./datos/lap_times.csv")
carreras <- rio::import(file = "./datos/races.csv")
pilotos <- rio::import(file = "./datos/drivers.csv")
circuitos_gp <- full_join(carreras, circuitos, c("circuitId" = "circuitId")) #asocio las carreras a su circuito
tiemposvuelta_x_carrera <- full_join(circuitos_gp, tiempos, c ("raceId" = "raceId")) #tiempo de las vueltas por cada carrera
tiemposvuelta_x_carrera <- full_join(tiemposvuelta_x_carrera, pilotos, c ("driverId" = "driverId")) %>% select(circuitId, name.y, driverId, driverRef, time.y, lap,position, year, country) #fusiono con el df de pilotos para asociar cada vuelta al nombre del piloto que la hizo
#calculo el record de cada circuito, filtrando el minimo de los tiempos en cada circuito
record_de_circuito <- tiemposvuelta_x_carrera %>% group_by(name.y) %>% slice_min(time.y, n=1)
#numero de records de circuito que tiene cada piloto
record_x_piloto <- record_de_circuito %>% group_by(driverId) %>% mutate(numero_records = sum(n())) %>% select(driverId, driverRef, numero_records) %>% distinct(driverRef, numero_records) %>% arrange(desc(numero_records))
# meter mapa del mundo con la ubicacion de los circuitos en la temporada 2021
#------------------------------------------------------------
objetos_no_borrar <- c("victorias_con_nombre", "n_carreras_nom", "mas_victorias")
rm(list = ls()[!ls() %in% objetos_no_borrar])#creo df de muertes de formula 1
muertesf1 <- data.frame(
"orden" = 1:42,
"driverRef" = c("Chet Miller", "Carl Scaraborough", "Onofre Marimon", "Manny Ayulo", "Bill Vukovich", "Alberto Ascari","Eugenio Castellotti", "Keith Andrews", "Pat O'Connor", "Luigi Musso", "Peter Collins", "Stuart Lewis-Evans", "Jerry Unser", "Bob Cortner", "Ivor Bueb", "Chris Bristow", "Alan Stacey", "Giulio Cabianca", "Wolfgang von Trips", "Carel Godin de Beaufort", "John Taylor", "Lorenzo Bandini", "Bob Anderson", "Jo Schlesser", "Gerhard Mitter", "Piers Courage", "Jochen Rindt", "Jo Siffert", "Roger Williamson", "François Cevert", "Peter Revson", "Helmuth Koinigg", "Mark Donohue", "Tom Pryce", "Ronnie Peterson", "Patrick Depailler", "Gilles Villeneuve", "Riccardo Paletti", "Elio de Angelis", "Roland Ratzenberger", "Ayrton Senna", "Jules Bianchi"),
"nationality" = c("American", "American", "Argentine", "American", "American", "Italian","Italian", "American", "American", "Italian", "British", "British", "American", "American", "British", "British", "British", "Italian", "German", "Dutch", "British", "Italian" , "British", "French", "German", "British", "Austrian", "Swiss", "British", "French", "American", "Austrian", "American", "British", "Swedish", "French", "Canadian", "Italian", "Italian", "Austrian", "Brazilian", "French"),
"dod" = c(1953, 1953, 1954, 1955, 1955, 1955, 1957, 1957, 1958,1958,1958,1958,1959,1959,1959,1960, 1960,1961,1961,1964,1966, 1967, 1967,1968,1969, 1970,1970,1971,1973,1973,1974,1974,1975,1977,1978,1980,1982,1982,1986,1994,1994,2014))
#no pongo las comillas en los años para que se creen directamente como observaciones numericas
#creo un df con todos los años para luego fusionarlo, ya que no hay muertes todos los años
anyos <- data.frame(
"orden" = 1:71,
"año" = c(1950:2020))
#sumatorio de las muertes por año
muertes_anyo <- muertesf1 %>% group_by(dod) %>% mutate(muertesxanyo = sum(n())) %>% distinct(dod, muertesxanyo)
#fusiono los 2 dfs para que tenga en cuenta los años donde no hay muertes
muertesf1_final <- full_join(muertes_anyo, anyos, c("dod" = "año")) %>% select(dod,muertesxanyo) %>% arrange(dod)
#convierto los N/A en 0, es decir, cuando no hay observaciones, ha habido 0 muertes
muertesf1_final[is.na(muertesf1_final)] <- 0
#grafico de las muertes por cada año + la tendencia negativa ea lo largo de la historia
gg_muertes <- ggplot(muertesf1_final, aes(x = dod, y = muertesxanyo )) + geom_point() + geom_line() + geom_smooth() + labs(x = "Año" , y = "Número de muertes")
gg_muertes
objetos_no_borrar <- c("victorias_con_nombre", "n_carreras_nom", "mas_victorias")
rm(list = ls()[!ls() %in% objetos_no_borrar])Tenemos pensado elaborar el trabajo en equipo sobre Formula 1, una competición de la que somos muy aficionados, entre otras cosas por la importancia que tienen los datos a la hora de formalizar las estrategias en la competición.
#mas posiciones remontadas en una carrera gran premio
tiempos <- rio::import(file = "./datos/lap_times.csv")
carreras <- rio::import(file = "./datos/races.csv")
resultados <- rio::import(file = "./datos/results.csv")
circuitos <- rio::import(file = "./datos/circuits.csv")
pilotos <- rio::import(file = "./datos/drivers.csv")
resultados[, c(6,9)] <- sapply(resultados[, c(6,9)], as.numeric) #transformo variables grid y positionOrder en numerico
str(resultados) # para comprobarlo
#> 'data.frame': 25140 obs. of 18 variables:
#> $ resultId : int 1 2 3 4 5 6 7 8 9 10 ...
#> $ raceId : int 18 18 18 18 18 18 18 18 18 18 ...
#> $ driverId : int 1 2 3 4 5 6 7 8 9 10 ...
#> $ constructorId : int 1 2 3 4 1 3 5 6 2 7 ...
#> $ number : chr "22" "3" "7" "5" ...
#> $ grid : num 1 5 7 11 3 13 17 15 2 18 ...
#> $ position : chr "1" "2" "3" "4" ...
#> $ positionText : chr "1" "2" "3" "4" ...
#> $ positionOrder : num 1 2 3 4 5 6 7 8 9 10 ...
#> $ points : num 10 8 6 5 4 3 2 1 0 0 ...
#> $ laps : int 58 58 58 58 58 57 55 53 47 43 ...
#> $ time : chr "1:34:50.616" "+5.478" "+8.163" "+17.181" ...
#> $ milliseconds : chr "5690616" "5696094" "5698779" "5707797" ...
#> $ fastestLap : chr "39" "41" "41" "58" ...
#> $ rank : chr "2" "3" "5" "7" ...
#> $ fastestLapTime : chr "1:27.452" "1:27.739" "1:28.090" "1:28.603" ...
#> $ fastestLapSpeed: chr "218.300" "217.586" "216.719" "215.464" ...
#> $ statusId : int 1 1 1 1 1 11 5 5 4 3 ...
#mayores remontadas de la historia, se resta posicion de salida - posicion final
puestos_remontados <- resultados %>% mutate(remontados = grid - positionOrder) %>% select(raceId, driverId, grid, positionOrder, remontados)
#de toda la historia
circuitos_gp <- full_join(carreras, circuitos, c("circuitId" = "circuitId")) %>% select(circuitId, name.y, raceId, year)
ptos_remont_carrera <- inner_join(puestos_remontados, circuitos_gp)
puestos_remont_piloto <- full_join(pilotos, ptos_remont_carrera, c("driverId" = "driverId")) %>% slice_max(remontados, n=10) %>% select(driverId, driverRef,name.y,year, raceId, grid, positionOrder, remontados)
#------------------------------
# de la hisotoria reciente
circuitos_gp_recient <- full_join(carreras, circuitos, c("circuitId" = "circuitId")) %>% select(circuitId, name.y, raceId, year) %>% filter(year >= 1995)
ptos_remont_carrera_recient <- inner_join(puestos_remontados, circuitos_gp_recient)
puestos_remont_piloto_recient <- full_join(pilotos, ptos_remont_carrera_recient, c("driverId" = "driverId")) %>% slice_max(remontados, n=10) %>% select(driverId, driverRef, name.y, year,raceId, grid, positionOrder, remontados) %>% slice(1:4,6:8,10) %>% arrange(desc(remontados))
ggremontados <- ggplot(puestos_remont_piloto_recient, aes(x = reorder(driverRef, remontados), remontados)) + geom_bar(stat = "identity") + coord_flip() + labs(x = "Pilotos", y = "Nº de puestos remontados" )
ggremontados
objetos_no_borrar <- c("victorias_con_nombre", "n_carreras_nom", "mas_victorias")
rm(list = ls()[!ls() %in% objetos_no_borrar])#se necesita tener cargado "n_carreras_nom", "victorias_con_nombre"
fotos_ALO_vs_HAM <- c("./imagenes/pilotos/alonso.png", "./imagenes/pilotos/hamilton.png")
fotos_esp_ing <- c("./imagenes/paises/espanya.png", "./imagenes/paises/uk.png")
n_carreras_alo_ham <- n_carreras_nom %>% filter(driverRef %in% c("alonso", "hamilton"))
n_victorias_alo_ham <- victorias_con_nombre %>% filter(driverRef %in% c("alonso", "hamilton"))
alo_vs_ham <- full_join(n_carreras_alo_ham, n_victorias_alo_ham, c("driverRef"= "driverRef")) %>% select( driverRef, numero_carreras, n_victorias) %>% add_column(fotos_esp_ing, fotos_ALO_vs_HAM)
library(gt)
alo_vs_ham_tabla <- alo_vs_ham %>% gt() %>% text_transform( locations = cells_body(columns = c(fotos_esp_ing)), fn = function(x) {gt::local_image(x, height = 50)}) %>% text_transform( locations = cells_body(columns = c(fotos_ALO_vs_HAM)), fn = function(x) {gt::local_image(x, height = 100)}) %>% tab_header(title = md("**Alonso vs Hamilton**"), subtitle = md("Comparación")) %>% cols_label(
driverRef = html(""),
numero_carreras = html("Nº carreras"),
n_victorias = html("Nº victorias"),
fotos_esp_ing = html("País"),
fotos_ALO_vs_HAM = html("")) %>%
tab_options(table.background.color = "gray13", table.font.color.light = "cyan") %>%
cols_align(align = "center",
columns = everything())
alo_vs_ham_tabla| Alonso vs Hamilton | ||||
|---|---|---|---|---|
| Comparación | ||||
| Nº carreras | Nº victorias | País | ||
| alonso | 323 | 32 | ||
| hamilton | 275 | 98 | ||
#audiencias
audiencias <- rio::import(file = "./datos/audienciasF1.csv")
ggaudiencias <- ggplot(audiencias, aes(x = Año, y = numero_espectadores)) +
geom_histogram (stat = "identity") +
labs(x = "Año", y = "Numero de espectadores" ) +
scale_x_continuous(
breaks = seq(2004, 2020, 1),
limits = c(2003, 2021)) #+ transition_reveal(Año)
ggaudiencias
rm(list = ls())#presupuestos
presupuestos <- read_excel("datos/presupuestos.xlsx")
gg_presup <- ggplot(presupuestos, aes(year, Presupuesto, color = Escuderia)) +
geom_point() + geom_line() +
labs(x = "Año", y = "Presupuesto en €" ) +
scale_x_continuous(
breaks = seq(2015, 2023, 1),
limits = c(2014, 2024)) +
scale_y_continuous( breaks = seq(0, 700000000, 100000000),
limits = c(0, 600000000))
ggplotly(gg_presup)Hemos encontrado en kaggle bastantes conjuntos de datos con los que poder trabajar, pero especialmente este, que posee gran variedad de datos en lo referente a pilotos, resultados, circuitos, tiempos, etc… Consideramos que para empezar a trabajar será suficiente, y en función de como vayamos dirigiendo el trabajo, buscaremos diferentes conjunto de datos con los que apoyarnos.
Con los datos que hemos encontrado, existen una serie de códigos que ya trabajan con estos datos, especialmente este, que ha conseguido realizar análisis con este conjunto de datos y varias ilustraciones muy llamativas, por lo que podremos tomarlo como referencia durante el inicio del trabajo
“Nadie es más rápido que el nano”